<?php
/**
 * 获取微信文章接口
 */
defined('IN_CMS') or exit('No permission resources.');

$userid = $_SESSION['userid'] ? $_SESSION['userid'] : (param::get_cookie('_userid') ? param::get_cookie('_userid') : param::get_cookie('userid'));
$siteid = param::get_cookie('siteid');
if(!$siteid) $siteid = get_siteid() ? get_siteid() : 1 ;
$url = urldecode($_GET['url']);
if (!$url) {
	json(0, '微信文章地址不能为空');
}

$html = dr_catcher_data($url);
if (!$html) {
	json(0, '没有获取到任何内容');
}

$preg = '<div class="rich_media_content " id="js_content" style="visibility: hidden;">';
if (preg_match('/'.$preg.'(.+)<\/div>/sU', $html, $mt)) {
	$body = trim($mt[1]);
	$body = str_replace(array('style="display: none;"', ''), '', $body);
	$body = str_replace('data-src=', 'src=', $body);
	// 下载远程图片
	if (intval($_GET['is_esi']) && preg_match_all("/(src)=([\"|']?)([^ \"'>]+)\\2/i", $body, $imgs)) {
		$upload_url = pc_base::load_config('system','upload_url');
		$upload_root = pc_base::load_config('system','upload_path');
		if (pc_base::load_config('system','attachment_file')) {
			$dir = $siteid.'/'.date('Y/md/');
		} else {
			$dir = date('Y/md/');
		}
		$uploadpath = $upload_url.$dir;
		$uploaddir = $upload_root.$dir;
		foreach ($imgs[3] as $img) {
			$ext = get_file_ext($img);
			if (!$ext) {
				continue;
			}
			// 下载图片
			if (intval($_GET['is_esi']) && strpos($img, 'http') === 0) {
				$arr = parse_url($img);
				$domain = $arr['host'];
				if ($domain) {
					$sitedb = pc_base::load_model('site_model');
					$data = $sitedb->select();
					$sites = array();
					foreach ($data as $t) {
						$site_domain = parse_url($t['domain']);
						if ($site_domain['port']) {
							$sites[$site_domain['host'].':'.$site_domain['port']] = $t['siteid'];
						} else {
							$sites[$site_domain['host']] = $t['siteid'];
						}
					}
					if (isset($sites[$domain])) {
						// 过滤站点域名
					} elseif (strpos($upload_url, $domain) !== false) {
						// 过滤附件白名单
					} else {
						if(strpos($img, '://') === false) continue;
						pc_base::load_sys_func('dir');
						dir_create($uploaddir);
						$filename = get_file_ext($img);
						$filename = substr(md5(SYS_TIME.uniqid().$body), rand(0, 20), 15).'.'.$filename;

						$newfile = $uploaddir.$filename;
						file_put_contents($newfile, dr_catcher_data($img));
						$fileext = get_file_ext($filename);
						// 图片处理
						if (is_image($newfile)) {
							// 图片压缩处理
							if (intval($_GET['image_reduce'])) {
								$image->reduce($savefile, $_GET['image_reduce']);
							}
							pc_base::load_sys_class('image');
							$image = new image();
							$siteinfo = getcache('sitelist', 'commons');
							$config = string2array($siteinfo[$siteid]['setting']);
							$watermark_enable = $config['watermark_enable'];
							if(intval($_GET['watermark']) && intval($config['watermark_enable'])) {
								$config['source_image'] = $newfile;
								$config['dynamic_output'] = false;
								$image->watermark($config);
							}
						}
						$filepath = $dir.$filename;
						$downloadedfile = array('filename'=>$filename, 'filepath'=>$filepath, 'filesize'=>filesize($newfile), 'fileext'=>$fileext);
						$aid = add($downloadedfile);
						$downloadedfiles[$aid] = $filepath;
						$body = str_replace($img, $uploadpath.$filename, $body);
					}
				}
			}
		}
	}
} else {
	echo $url;exit;
	json(0, '没有获取到文章内容');
}
if (preg_match('/<meta property="og:title" content="(.+)"/U', $html, $mt)) {
	$title = trim($mt[1]);
} else {
	json(0, '没有获取到文章标题');
}

json(1, '导入成功', array(
	'title' => $title,
	'keyword' => get_keywords($title),
	'content' => $body,
));
/**
* 统一返回json格式并退出程序
*/
function json($code, $msg, $data = array()){
	echo dr_array2string(dr_return_data($code, $msg, $data));exit;
}
/**
 * 将数组转换为字符串
 *
 * @param	array	$data	数组
 * @return	string
 */
function dr_array2string($data) {
	if (version_compare(PHP_VERSION,'5.4.0', '<')) {
		return $data ? json_encode($data) : '';
	} else{
		return $data ? json_encode($data, JSON_UNESCAPED_UNICODE) : '';
	}
}
function get_keywords($kw) {
	if (!$kw) {
		return '';
	}
	$cfg_bdqc_qcnum = pc_base::load_config('system', 'baidu_qcnum') ? pc_base::load_config('system', 'baidu_qcnum') : 10;
	if (pc_base::load_config('system', 'keywordapi')==1) {
		$baiduapi = pc_base::load_sys_class('baiduapi');
		$data = array(
			'title' => $kw,
			'content' => $kw,
		);
		$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
		$baidu = $baiduapi->get_data('https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword', $data, 1);
		if ($baidu && $baidu['data']['items']) {
			$n = 0;
			$resultstr = '';
			foreach ($baidu['data']['items'] as $t) {
				$resultstr .= ','.$t['tag'];
				$n++;
				if( $n >= $cfg_bdqc_qcnum ) break;
			}
		}
		return trim($resultstr, ',');
	} else if (pc_base::load_config('system', 'keywordapi')==2) {
		$XAppid = pc_base::load_config('system', 'xunfei_aid');
		$Apikey = pc_base::load_config('system', 'xunfei_skey');
		$fix = 0; //如果错误日志提示【time out|ilegal X-CurTime】，需要把$fix变量改为 100 、200、300、等等，按实际情况调试，只要是数字都行
		$XParam = base64_encode(json_encode(array(
			"type"=>"dependent",
		)));
		$XCurTime = SYS_TIME - $fix;
		$XCheckSum = md5($Apikey.$XCurTime.$XParam);
		$headers = array();
		$headers[] = 'X-CurTime:'.$XCurTime;
		$headers[] = 'X-Param:'.$XParam;
		$headers[] = 'X-Appid:'.$XAppid;
		$headers[] = 'X-CheckSum:'.$XCheckSum;
		$headers[] = 'Content-Type:application/x-www-form-urlencoded; charset=utf-8';
		$rt = json_decode(file_get_contents("http://ltpapi.xfyun.cn/v1/ke", false, stream_context_create(array(
			'http' => array(
				'method' => 'POST',
				'header' => $headers,
				'content' => http_build_query(array(
					'text' => $kw,
				)),
				'timeout' => 15*60
			)
		))), true);
		if (!$rt) {
			//showmessage('讯飞接口访问失败');
			return '';
		} elseif ($rt['code']) {
			//showmessage('讯飞接口: '.$rt['desc']);
			return '';
		} else {
			$n = 0;
			$resultstr = '';
			foreach ($rt['data']['ke'] as $t) {
				$resultstr .= ','.$t['word'];
				$n++;
				if( $n >= $cfg_bdqc_qcnum ) break;
			}
			return trim($resultstr, ',');
		}
	} else {
		$phpanalysis = pc_base::load_sys_class('phpanalysis');
		$phpanalysis = new phpanalysis('utf-8', 'utf-8', false);
		$phpanalysis->LoadDict();
		$phpanalysis->SetSource($kw);
		$phpanalysis->StartAnalysis(true);
		return $phpanalysis->GetFinallyKeywords($cfg_bdqc_qcnum);
	}
	return '';
}
/**
 * 附件添加如数据库
 * @param $uploadedfile 附件信息
 */
function add($uploadedfile) {
	$userid = $_SESSION['userid'] ? $_SESSION['userid'] : (param::get_cookie('_userid') ? param::get_cookie('_userid') : param::get_cookie('userid'));
	$siteid = param::get_cookie('siteid');
	if(!$siteid) $siteid = get_siteid() ? get_siteid() : 1 ;
	$att_db = pc_base::load_model('attachment_model');
	$uploadedfile['module'] = trim($_GET['module']);
	$uploadedfile['catid'] = intval($_GET['catid']);
	$uploadedfile['siteid'] = $siteid;
	$uploadedfile['userid'] = $userid;
	$uploadedfile['uploadtime'] = SYS_TIME;
	$uploadedfile['uploadip'] = ip();
	$uploadedfile['status'] = pc_base::load_config('system','attachment_stat') ? 0 : 1;
	$uploadedfile['authcode'] = md5($uploadedfile['filepath']);
	$uploadedfile['filename'] = file_name($uploadedfile['filename']);
	$uploadedfile['isimage'] = in_array($uploadedfile['fileext'], array('gif', 'jpg', 'jpeg', 'png', 'bmp')) ? 1 : 0;
	$aid = $att_db->api_add($uploadedfile);
	$uploadedfiles[] = $uploadedfile;
	return $aid;
}
/**
 * 获取附件名称
 * @param $fileext 附件扩展名
 */
function getname($fileext){
	return substr(md5(SYS_TIME.uniqid()), rand(0, 20), 15).'.'.$fileext;
}
/**
 * 获取文件名
 */
function file_name($name) {
	strpos($name, '/') !== false && $name = trim(strrchr($name, '/'), '/');
	return substr($name, 0, strrpos($name, '.'));
}
// 获取远程附件扩展名
function get_file_ext($url) {

	$arr = array('gif', 'jpg', 'jpeg', 'png', 'webp');
	$ext = str_replace('.', '', trim(strtolower(strrchr($url, '.')), '.'));
	if ($ext && in_array($ext, $arr)) {
		return $ext; // 满足扩展名
	} elseif ($ext && strlen($ext) < 4) {
		return ''; // 表示不是图片扩展名了
	}

	foreach ($arr as $t) {
		if (stripos($url, $t) !== false) {
			return $t;
		}
	}

	return '';
}
/**
 * 调用远程数据
 *
 * @param	string	$url
 * @param	intval	$timeout 超时时间，0不超时
 * @return	string
 */
function dr_catcher_data($url, $timeout = 0) {

    // 获取本地文件
	if (strpos($url, 'file://')  === 0) {
		return file_get_contents($url);
	}

    // curl模式
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        if (substr($url, 0, 8) == "https://") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 最大执行时间
        $timeout && curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $data = curl_exec($ch);
        $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $errno = curl_errno($ch);
        if ($errno) {
            //log_message('error', '获取远程数据失败['.$url.']：（'.$errno.'）'.curl_error($ch));
        }
        curl_close($ch);
        if ($code == 200) {
            return $data;
        } elseif ($errno == 35) {
            // 当服务器不支持时改为普通获取方式
        } else {
            return '';
        }
    }

	//设置超时参数
	if ($timeout && function_exists('stream_context_create')) {
		// 解析协议
		$opt = array(
			'http' => array(
				'method'  => 'GET',
				'timeout' => $timeout,
			),
			'https' => array(
				'method'  => 'GET',
				'timeout' => $timeout,
			)
		);
		$ptl = substr($url, 0, 8) == "https://" ? 'https' : 'http';
		$data = @file_get_contents($url, 0, stream_context_create(array(
			$ptl => $opt[$ptl]
		)));
	} else {
		$data = @file_get_contents($url);
	}

    return $data;
}
?>